<?php
/**
 * APP端的活动信息（整理Activity.php代码）
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-03-28
 * Time: 下午 11:26
 */
namespace App;
use Model\ActivityCouponMod;
use Model\ActivityMemberMod;
use Model\ActivityMemberTreasureMod;
use Model\ActivityMod;
use Model\GiveCouponMod;
use Model\InviteMod;
use Model\ShareMod;
use Model\StoreCouponMod;
use Model\StoreManageMod;
use Model\StoreMod;
use Pri\snapshot\CouponSnapshot;
use Pub\cache\Cache;
use Pub\date\Date;

class ActivityA extends Action
{
	private $Activity = null;  //活动
    private $ActivityMember = null;  //活动会员
    private $ActivityMemberTreasure = null;  //会员抢到的宝藏
    private $Share = null;   //分享
    private $Invite = null;  //邀请分享记录
    private $Store = null;  //门店
    private $StoreMange = null; //门店经营范围
    private $ActivityCoupon = null;  //活动投放的卡券
    private $StoreCoupon = null;  //门店卡券
    private $GiveCoupon = null;  //门店发券记录

    private $_activity_coupon = array();  //活动的卡券信息

	public function __construct()
	{
		parent::__construct();
		$this->Activity = new ActivityMod();
	}

    /**
     * 获取列表
     * @param limit 获取下标与数量
     */
    public function getList()
    {
        $_list = $this->Activity->ali($this->_gpc['limit']);
        if (count($_list)) {
            foreach ($_list as $_k => $_v) {
                $_list[$_k]['status'] = Date::time2time($_v['start'],$_v['end']);
                $_list[$_k]['start'] = date('Y-m-d H:i', $_v['start']);
                $_list[$_k]['end'] = date('Y-m-d H:i', $_v['end']);
                $_list[$_k]['cover'] = tomedia($_v['cover']);
            }
            $this->_result = array('status' => 'success', 'data' => $_list);
        }
        $this->result($this->_result);
    }

    /**
     * 获取APP端活动所有信息
     * @param activity_id 活动id
     * @param uid 用户id
     */
    public function get()
    {
        $_data = Cache::get(Cache::ACTIVITY_INFO,array('activity_id'=>$this->_gpc['activity_id']));
        if(!$_data || KUYUAN_DEBUG){
            $_data = $this->getActivity($this->Activity,$this->_gpc['activity_id']);
            Cache::set(Cache::ACTIVITY_INFO,$_data,array('activity_id'=>$this->_gpc['activity_id']));
            $this->_result = array('status'=>'success','cache'=>0);
        }else{
            $this->_result = array('status'=>'success','cache'=>1);
        }
        //活动进行状态
        $_data['time_status'] = Date::time2time($_data['start'],$_data['end']);
        $this->_result['data'] = $_data;
        $this->result($this->_result);
    }

    /**
     * 获取用户可打开宝箱的数据
     * @param activity_id 活动id
     * @param uid 用户id
     * @param init_bz_number 活动可开宝箱的基础数量
     */
    public function getUserOpenBzNumber()
    {
        $this->ActivityMember = new ActivityMemberMod();
        $this->ActivityMemberTreasure = new ActivityMemberTreasureMod();
        $_activity_member = $this->ActivityMember->findOne(array('uid'=>$this->_gpc['uid'],'activity_id'=>$this->_gpc['activity_id']),array('open_num'));
        $_can_open_number = $this->_gpc['init_bz_number']+$_activity_member['open_num'];
        $_already_open_number = abs($this->ActivityMemberTreasure->sum(array('uid'=>$this->_gpc['uid'],'activity_id'=>$this->_gpc['activity_id'],'source'=>1),'number'));
        $_data = array('can_open_number'=>$_can_open_number,'already_open_number'=>$_already_open_number);
        $this->_result = array('status'=>'success','data'=>$_data);
        $this->result($this->_result);
    }

    /**
     * 注册活动
     * @param uid 用户id
     * @param activity_id 活动id
     * @param share_uid 分享的用户id  等于0不是分享进入的
     * @param share_take 是否达到分享奖励的条件
     */
    public function register()
    {
        $this->ActivityMember = new ActivityMemberMod();
        $_activity_member = $this->ActivityMember->findOne(array('uid'=>$this->_gpc['uid'],'activity_id'=>$this->_gpc['activity_id']),array('id'));
        $_add_friend = false;
        if(!$_activity_member){
            if($this->_gpc['share_uid'] > 0 && $this->_gpc['share_take'] == 1){
                $_add_friend = $this->addFriend();
            }
            $_register = $this->ActivityMember->insert(array(
                'uniacid' => $this->_uniacid,
                'activity_id' => $this->_gpc['activity_id'],
                'uid' => $this->_gpc['uid'],
                'exchange_number'=>mt_rand(100000,999999),
                'time' => TIMESTAMP
            ));
            if($_register){
                $_add_friend = $_add_friend ? 1 : 0;
                $this->_result = array('status'=>'success','add_friend'=>$_add_friend);
            }
        }else{
            $this->_result = array('status'=>'success');
        }
        $this->result($this->_result);
    }

    /**
     * 添加活动好友
     */
    public function addFriend()
    {
        //验证添加好友sign
        $_add_friend_sign_cache = Cache::get(Cache::ADD_FRIEND_SIGN,array('id'=>$this->_gpc['activity_id'].'_'.$this->_gpc['uid'].'_'.$this->_gpc['share_uid']));
        if(!$_add_friend_sign_cache) return false;
        $_add_friend_sign = sha1($this->_gpc['activity_id'].'_'.$this->_gpc['uid'].'_'.$this->_gpc['share_uid']);
        if($_add_friend_sign_cache != $_add_friend_sign) return false;

        //验证被添加用户是否存在
        if(!$this->ActivityMember->findOne(array('uid'=>$this->_gpc['share_uid'],'activity_id'=>$this->_gpc['activity_id']),array('id'))) return false;

        //添加好友
        $this->Share = new ShareMod();
        $_share = $this->Share->findOne(array('activity_id'=>$this->_gpc['activity_id'],'open_share'=>1),array('add_bz'));
        if($_share){
            $this->Invite = new InviteMod();
            $this->Invite->insert(array(
                'activity_id'=>$this->_gpc['activity_id'],
                'share_uid'=>$this->_gpc['share_uid'],
                'invite_uid'=>$this->_gpc['uid'],
                'open_count'=>$_share['add_bz'],
                'time'=>TIMESTAMP
            ));
            return true;
        }
        return false;
    }


    /**
     * APP端活动领券页面列表
     * @param limit 请求下标数量
     * @param activity_id 活动id
     */
    public function activityGetCoupon()
    {
        $this->Store = new StoreMod();
        $_sell_range = array();   //门店的经营范围，用户搜索门店的经营类型
        if($this->_gpc['search_status'] == 1){
            $this->StoreMange = new StoreManageMod();
            $_store_manage = $this->StoreMange->findAll(array('uniacid'=>$this->_uniacid,'status'=>1,'name like'=>'%'.$this->_gpc['search_keyword'].'%'),array('order'=>array('id','asc')),array('id'));
            if(count($_store_manage) > 0){
                foreach($_store_manage as $_v){
                    $_sell_range[] = $_v['id'];
                }
            }else{
                $this->_result = array('status'=>'error');
                $this->result($this->_result);
            }
        }
        $_list = $this->Store->activityGetCoupon($this->_gpc['activity_id'],$this->_gpc['limit'],$_sell_range);
        if(count($_list) > 0){
            foreach($_list as $_k=>$_v){
                $_coupons = $this->Store->activityStoreGetCoupon($_v['store_id'],$this->_gpc['activity_id']);
                foreach($_coupons as $_ka=>$_va){
                    $_cost = $this->costToStrcost($_va['type'],$_va['cost']);
                    $_coupons[$_ka]['user_number'] = abs($_va['user_number']);
                    $_coupons[$_ka]['give_number'] = abs($_va['give_number']);
                    $_coupons[$_ka]['number'] = abs($_va['number']);
                    $_coupons[$_ka]['type'] = $_cost['type'];
                    $_coupons[$_ka]['coupon_type'] = $_va['type'];
                    $_coupons[$_ka]['cost'] = $_cost['face_value'];
                    $_coupons[$_ka]['time'] = $this->limitTimeTostring($_va['use_limit_type'],$_va['limit_time']);
                    //S用户已领数量,判断用户是否已经领了足够的卡券，如果足够则不可以领取了，是否可以领取
                    $_coupons[$_ka]['received_number'] = $this->userTreasureNumber($this->_gpc['uid'],$this->_gpc['activity_id'],$_va['treasure_id'],'coupon');;
                    //E判断用户是否已经领了足够的卡券，如果足够则不可以领取了，是否可以领取
                    //S卡券是否已经过期
                    $_coupons[$_ka]['expire'] = false;
                    if($_va['use_limit_type'] == 2){
                        if($_va['limit_time']+86400-1 < TIMESTAMP){
                            $_coupons[$_ka]['expire'] = true;
                        }
                    }
                    //E卡券是否已经过期
                    //卡券封面
                    $_images = json_decode($_va['images'],true);
                    if(count($_images) > 0){
                        $_coupons[$_ka]['cover'] = tomedia($_images[0]);
                    }
                }
                $_list[$_k]['coupons'] = $_coupons;
                $_list[$_k]['logo'] = tomedia($_v['logo']);
            }
            unset($_coupons);
            $this->_result = array('status'=>'success','data'=>$_list);
        }
        $this->result($this->_result);
    }

    /**
     * APP端领券页面领卡券
     */
    public function getCoupon()
    {
        $this->ActivityCoupon = new ActivityCouponMod();
        $this->_activity_coupon = $this->ActivityCoupon->findOne(array('id'=>$this->_gpc['treasure_id']),array('coupon_id','number','user_number','give_number','use_limit_type','limit_time'));
        //step 1、验证用户领取卡券数量
        $this->checkReceivedNumber();   //验证用户领取的数量

        //step 2、验证卡券库存
        if($this->_activity_coupon['give_number'] >= $this->_activity_coupon['number']){
            $this->_result = array('status'=>'error','err_status'=>8,'err_msg'=>'卡券库存不足');
            $this->result($this->_result);
        }

        //step 3、验证卡券是否过期
        if($this->_activity_coupon['use_limit_type'] == 2){
            if($this->_activity_coupon['limit_time']+86400-1 < TIMESTAMP){
                $this->_result = array('status'=>'error','err_status'=>7,'err_msg'=>'卡券已过期');
                $this->result($this->_result);
            }
        }

        //step 4、新增give_number
        $this->ActivityCoupon->math(array('give_number +'=>1),array('id'=>$this->_gpc['treasure_id']));

        //step5、领取卡券
        if($this->addMemberTreasure()){
            $this->_activity_coupon = $this->ActivityCoupon->findOne(array('id'=>$this->_gpc['treasure_id']),array('give_number'));
            $_data = array();
            $_data['give_number'] = $this->_activity_coupon['give_number'];
            $_data['received_number'] = $this->userTreasureNumber($this->_gpc['uid'],$this->_gpc['activity_id'],$this->_gpc['treasure_id'],'coupon');
            //记录门店发券记录
            $this->storePutCouponRecord();
            $this->_result = array('status'=>'success','data'=>$_data);
            $this->result($this->_result);
        }else{
            $this->_result = array('status'=>'error','err_status'=>6,'err_msg'=>'卡券领取失败');
            $this->result($this->_result);
        }

    }

    /**
     * 验证用户领取的数量
     */
    private function checkReceivedNumber()
    {
        if($this->_activity_coupon['user_number'] > 0){
            $_received_number = $this->userTreasureNumber($this->_gpc['uid'],$this->_gpc['activity_id'],$this->_gpc['treasure_id'],'coupon');
            if($_received_number >= $this->_activity_coupon['user_number']){
                $this->_result = array('status'=>'error','err_status'=>9,'err_msg'=>'该卡券每个用户只能领取'.$this->_activity_coupon['user_number'].'张');
                $this->result($this->_result);
            }
        }
    }

    /**
     * 新增用户领取宝箱记录
     * @return boolean 是否新增成功
     */
    private function addMemberTreasure()
    {
        $_data = array(
            'uid'=>$this->_gpc['uid'],
            'activity_id'=>$this->_gpc['activity_id'],
            'treasure_id'=>$this->_gpc['treasure_id'],
            'source'=>2
        );
        $this->ActivityMemberTreasure = new ActivityMemberTreasureMod();
        $_one = $this->ActivityMemberTreasure->findOne($_data,array('id'));
        $this->addCouponSnapshot();
        if($_one){
            return $this->ActivityMemberTreasure->math(array('number +'=>1),array('id'=>$_one['id']));
        }else{
            $_data['type'] = 3;
            return $this->ActivityMemberTreasure->insert($_data);
        }
    }

    /**
     * 新增卡券快照
     */
    private function addCouponSnapshot()
    {
        $_past_time = 1;
        if($this->_activity_coupon['use_limit_type'] == 2){
            $_past_time = $this->_activity_coupon['limit_time'];
        }else if($this->_activity_coupon['use_limit_type'] == 3){
            $_past_time = strtotime(date('Y-m-d')) + $this->_activity_coupon['limit_time'] * 86400;
        }
        $this->StoreCoupon = new StoreCouponMod();
        $_store_coupon = $this->StoreCoupon->findOne(array('id'=>$this->_activity_coupon['coupon_id']),array('name','images','type','cost','rule','edit_time'));
        $_cost = $this->costToStrcost($_store_coupon['type'],$_store_coupon['cost']);
        $_images = json_decode($_store_coupon['images'],true);
        $_data = array(
            'activity_id'=>$this->_gpc['activity_id'],
            'store_id'=>$this->_gpc['store_id'],
            'uid'=>$this->_gpc['uid'],
            'coupon_id'=>$this->_activity_coupon['coupon_id'],
            'activity_coupon_id'=>$this->_gpc['treasure_id'],
            'type'=>$_store_coupon['type'],
            'name'=>$_store_coupon['name'],
            'cost'=>$_cost['face_value'],
            'rule'=>$_store_coupon['rule'],
            'cost_type'=>$_cost['type'],
            'past_time'=>$_past_time,
            'edit_time'=>$_store_coupon['edit_time']
        );
        if(count($_images) > 0){
            $_data['images'] = $_images;
            $_data['cover'] = $_images[0];
        }
        unset($_images);
        $CouponSnapshot = new CouponSnapshot($_data);
        $CouponSnapshot->save();
    }

    /**
     * 记录门店发券记录
     */
    private function storePutCouponRecord()
    {
        if(!$this->GiveCoupon instanceof GiveCouponMod) $this->GiveCoupon = new GiveCouponMod();
        $this->GiveCoupon->insert(array(
            'store_id'=>$this->_gpc['store_id'],
            'time'=>TIMESTAMP
        ));
    }
}